package edu.ncsu.csc.ip.routing.ls;

import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;

/**
 * Class <code>link_state</code>
 * 
 *  Runs LinkState to comply with project 3 description 
 * 
 * @author Moin Ayazifar <mayazif@ncsu.edu>
 * @author Steven Elliott <sdelliot@ncsu.edu>
 * 
 */

public class link_state {

	public static Comparator<Node> NodeNameComparator = new Comparator<Node>() {
		public int compare(Node node1, Node node2) {
			// ascending order
			return Integer.valueOf(node1.getName()).compareTo(
					Integer.valueOf(node2.getName()));
		}
	};

	public static void main(String[] args) throws IOException {
		try {
			LinkState linkState = new LinkState();
			linkState.loadGraph(args[0]);
			printResults(args[1], args[2], linkState);
			printResults(args[2], args[1], linkState);
		} catch (Exception e) {
			System.err
					.println("USAGE:\n java link_state <file name> <source node> <dest node>\n Example:\njava link_state ./network/node1.txt 1 10");
			e.printStackTrace();
		}
	}

	public static void printResults(String sourceString,
			String destinationString, LinkState linkState) {
		linkState.initialize();
		Node source = linkState.nodesMap.get(sourceString);
		Node destination = linkState.nodesMap.get(destinationString);
		linkState.populateLeastCostPaths(source);

		System.out.println("Source: " + source);
		System.out.println("Destination: " + destination);
		System.out.println("Cost: " + destination.getMinCost());
		System.out.println("Thru Node: " + linkState.getNextNode(destination));
		System.out
				.println("Path: " + linkState.leastCostPathTo(destination));
		System.out.println();

		System.out.println("---------Routing Table of Node " + source
				+ "-------------");
		System.out.println("DestNode	ThruNode	Cost	Path");
		Node[] nodes = linkState.nodesMap.values().toArray(
				new Node[linkState.nodesMap.size()]);
		Arrays.sort(nodes, NodeNameComparator);
		for (Node v : nodes) {
			if (!v.equals(source))
				System.out.println(v + "		" + linkState.getNextNode(v) + "		"
						+ v.getMinCost() + "	" + linkState.leastCostPathTo(v));
		}
		System.out.println("------------------------------------------\n\n");
	}
}
